package com.zyw.mvc.bind;

import org.springframework.util.StringUtils;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * @author vill on 2014/8/11 22:21.
 * @desc
 */
public class CustomSqlDateEditor extends PropertyEditorSupport {

    private final SimpleDateFormat dateFormat;
    private final boolean allowEmpty;
    private final int exactDateLength;

    public CustomSqlDateEditor(SimpleDateFormat dateFormat,
                               boolean allowEmpty) {
        this.dateFormat = dateFormat;
        this.allowEmpty = allowEmpty;
        this.exactDateLength = -1;
    }

    public CustomSqlDateEditor(SimpleDateFormat dateFormat,
                               boolean allowEmpty,
                               int exactDateLength) {
        this.dateFormat = dateFormat;
        this.allowEmpty = allowEmpty;
        this.exactDateLength = exactDateLength;
    }

    /**
     * Sets the property value by parsing a given String.  May raise
     * java.lang.IllegalArgumentException if either the String is
     * badly formatted or if this kind of property can't be expressed
     * as text.
     *
     * @param text The string to be parsed.
     */
    public void setAsText(String text) throws IllegalArgumentException {
//        super.setAsText(text);
        if (this.allowEmpty && !StringUtils.hasText(text)) {
            setValue(null);
        } else {
            if (text != null && this.exactDateLength >= 0
                    && text.length() != this.exactDateLength) {
                throw new IllegalArgumentException("Could not parse date: it is not exactly"
                        + this.exactDateLength + "characters long");
            }
            try {
                setValue(new java.sql.Date(this.dateFormat.parse(text).getTime()));
            } catch (ParseException e) {
                throw new IllegalArgumentException("Could not parse date: "
                        + e.getMessage(), e);
            }
        }
    }

    /**
     * Gets the property value as a string suitable for presentation
     * to a human to edit.
     *
     * @return The property value as a string suitable for presentation
     * to a human to edit.
     * <p>   Returns "null" is the value can't be expressed as a string.
     * <p>   If a non-null value is returned, then the PropertyEditor should
     * be prepared to parse that string back in setAsText().
     */
    public String getAsText() {
        java.sql.Date date = (java.sql.Date) getValue();
        return date != null ? this.dateFormat.format(date) : "";
    }
}
